<template>
  <div class="chart-container">
    <div class="chart-header" v-if="title">
      <div class="chart-title">{{ title }}</div>
    </div>
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';

// 添加内部currentDate状态
const currentDate = ref(new Date());

const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  chartType: {
    type: String,
    default: 'line' // 'line', 'bar', 'pie'
  },
  selectedDate: {
    type: Date,
    default: () => new Date()
  }
});

const chartRef = ref(null);
const chartInstance = ref(null);

onMounted(() => {
  if (chartRef.value) {
    // 确保容器有正确的尺寸
    const container = chartRef.value;
    if (container.offsetHeight === 0) {
      container.style.height = '450px';
    }
    
    // 初始化图表
    chartInstance.value = echarts.init(container);
    
    // 根据类型渲染对应的图表
    if (props.chartType === 'line') {
      renderLineChart();
    } else if (props.chartType === 'bar') {
      renderBarChart();
    } else if (props.chartType === 'pie') {
      renderPieChart();
    }
    
    // 监听窗口大小变化
    const handleResize = () => {
      if (chartInstance.value) {
        chartInstance.value.resize();
      }
    };
    
    window.addEventListener('resize', handleResize);
    
    // 组件卸载时清理
    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize);
      if (chartInstance.value) {
        chartInstance.value.dispose();
        chartInstance.value = null;
      }
    });
  }
});

const renderLineChart = () => {
  if (!chartRef.value) return

  const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  const lowRisk = [20, 18, 15, 23, 25, 33, 28, 25, 27, 22, 18, 16]
  const mediumRisk = [15, 12, 10, 18, 20, 25, 22, 18, 16, 14, 12, 10]
  const highRisk = [5, 4, 6, 8, 12, 18, 15, 10, 8, 6, 5, 4]
  const pestTrend = [30, 28, 26, 42, 50, 65, 58, 46, 44, 35, 30, 25]

  chartInstance.value.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['低危险', '中危险', '高危险', '虫害趋势'],
      top: '4%',
      itemGap: 12
    },
    grid: {
      left: '30px',
      right: '55px',
      bottom: '6%',
      top: '22%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLabel: {
        rotate: 0,
        interval: 0,
        fontSize: 13,
        show: true,
        hideOverlap: false,
        padding: [0, 0, 15, 0]
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '风险分布',
        min: 0,
        max: 80,
        interval: 20,
        position: 'left',
        axisLabel: {
          formatter: '{value}',
          margin: 8,
          fontSize: 13
        },
        nameTextStyle: {
          padding: [0, 0, 0, -5]
        }
      },
      {
        type: 'value',
        name: '虫害指数',
        min: 0,
        max: 70,
        interval: 10,
        position: 'right',
        offset: 0,
        axisLabel: {
          formatter: function(value) {
            // 使用更精确的对齐方式
            let numStr = value.toString();
            // 个位数前面加一个空格
            if (value < 10) {
              numStr = ' ' + numStr;
            }
            return numStr;
          },
          margin: 8,
          fontSize: 13
        },
        nameTextStyle: {
          padding: [0, -5, 0, 0]
        }
      }
    ],
    series: [
      {
        name: '低危险',
        type: 'bar',
        stack: '风险分布',
        data: lowRisk,
        barCategoryGap: '5%', // 添加类目间距调整
      },
      {
        name: '中危险',
        type: 'bar',
        stack: '风险分布',
        data: mediumRisk
      },
      {
        name: '高危险',
        type: 'bar',
        stack: '风险分布',
        data: highRisk
      },
      {
        name: '虫害趋势',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        lineStyle: {
          width: 4
        },
        symbolSize: 8,
        data: pestTrend
      }
    ]
  });
  
  // 清除之前的事件监听
  chartInstance.value.off('mousemove');
  chartInstance.value.off('mouseout');
  
  // 由于现在使用内置的axisPointer功能，不再需要自定义的辅助线逻辑
  // 但我们保留mouseout事件处理，以确保离开图表时清除任何可能的标记
  chartInstance.value.on('mouseout', () => {
    chartInstance.value.setOption({
      series: [{
        markLine: {
          data: []
        }
      }]
    }, false);
  });
};

const renderBarChart = () => {           //气象情况
  // 获取选定日期及其后6天的日期
  const days = [];
  const startDate = currentDate.value || new Date();
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(startDate);
    date.setDate(startDate.getDate() + i);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    days.push(`${month}/${day}`);
  }
  
  // 根据选定日期生成对应的气象数据
  // 这里使用一个简单的算法基于日期生成数据，实际应用可能需要从API获取真实数据
  const temperature = [];
  const rainfall = [];
  const humidity = [];
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(startDate);
    date.setDate(startDate.getDate() + i);
    const dayOfMonth = date.getDate();
    const monthOfYear = date.getMonth() + 1;
    
    // 生成基于日期的伪随机温度 (20-28°C)
    const tempBase = 20 + ((dayOfMonth * monthOfYear) % 9);
    temperature.push(tempBase);
    
    // 生成基于日期的伪随机降水量 (0-45mm)
    const rainBase = ((dayOfMonth + monthOfYear) % 5 === 0) ? 35 + (dayOfMonth % 11) : (dayOfMonth % 3 === 0 ? 10 + (dayOfMonth % 11) : 0);
    rainfall.push(rainBase);
    
    // 生成基于日期的伪随机湿度 (60-85%)
    const humidityBase = 60 + ((dayOfMonth + monthOfYear * 2) % 26);
    humidity.push(humidityBase);
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#eee',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      formatter: function(params) {
        let res = params[0].name + '<br/>';
        params.forEach(item => {
          let value = item.value;
          let unit = '';
          if (item.seriesName.includes('温度')) unit = '°C';
          if (item.seriesName.includes('降水量')) unit = 'mm';
          if (item.seriesName.includes('湿度')) unit = '%';
          
          res += `<div style="display:flex;align-items:center;margin:5px 0;">
                   <span style="display:inline-block;width:10px;height:10px;background:${item.color};margin-right:5px;"></span>
                   <span style="margin-right:5px;">${item.seriesName}:</span>
                   <span style="font-weight:bold;">${value}${unit}</span>
                 </div>`;
        });
        return res;
      },
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: 'rgba(200, 225, 255, 0.6)'
        }
      }
    },
    legend: {
      data: ['温度(°C)', '降水量(mm)', '湿度(%)'],
      top: 6,
      itemGap: 15
    },
    grid: {
      top: '15%',
      right: '10%',
      bottom: '15%',
      left: '10%',
      containLabel: true,
      height: '75%'
    },
    xAxis: {
      type: 'category',
      data: days,
      axisLine: {
        lineStyle: {
          color: '#999'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        interval: 0,
        fontSize: 11,
        show: true,
        hideOverlap: false,
        padding: [5, 0, 5, 0]
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '温度/湿度',
        min: 0,
        max: 100,
        interval: 20,
        position: 'left',
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        },
        axisLabel: {
          formatter: '{value}',
          margin: 8,
          fontSize: 11
        },
        nameTextStyle: {
          padding: [0, 0, 0, -5],
          fontSize: 11
        }
      },
      {
        type: 'value',
        name: '降水量',
        min: 0,
        max: 50,
        interval: 10,
        position: 'right',
        offset: 0,
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          formatter: '{value} mm',
          margin: 8,
          fontSize: 11
        },
        nameTextStyle: {
          padding: [0, -5, 0, 0],
          fontSize: 11
        }
      }
    ],
    series: [
      {
        name: '温度(°C)',
        type: 'line',
        smooth: true,
        data: temperature,
        symbolSize: 5,
        lineStyle: {
          width: 1.5
        },
        itemStyle: {
          color: '#FF9F45'
        }
      },
      {
        name: '降水量(mm)',
        type: 'bar',
        yAxisIndex: 1,
        data: rainfall,
        barWidth: '40%',
        barCategoryGap: '4%',
        itemStyle: {
          color: '#5470C6'
        }
      },
      {
        name: '湿度(%)',
        type: 'line',
        smooth: true,
        data: humidity,
        symbolSize: 5,
        lineStyle: {
          width: 1.5
        },
        itemStyle: {
          color: '#91CC75'
        }
      }
    ]
  };
  
  // 创建图表
  chartInstance.value.setOption(option);
  
  // 确保图表尺寸正确
  setTimeout(() => {
    chartInstance.value.resize();
  }, 50);
};

// 添加饼图渲染方法
const renderPieChart = () => {
  // 使用当前日期生成基于日期的动态数据
  const dateStr = currentDate.value.getDate();
  const monthStr = currentDate.value.getMonth() + 1;
  
  // 创建特定日期的适度差异数据
  let occupancyData = [];
  
  // 特殊处理3月24-26日，使这些日期有适度差异
  if (monthStr === 3 && dateStr === 24) {
    // 3月24日 - 茶民宿占比稍高
    occupancyData = [
      { value: 35, name: '茶民宿' },
      { value: 18, name: '茶博物馆' },
      { value: 22, name: '茶馆' },
      { value: 15, name: '文化景点' },
      { value: 20, name: '活动景点' }
    ];
  } else if (monthStr === 3 && dateStr === 25) {
    // 3月25日 - 茶馆占比稍高
    occupancyData = [
      { value: 25, name: '茶民宿' },
      { value: 22, name: '茶博物馆' },
      { value: 35, name: '茶馆' },
      { value: 18, name: '文化景点' },
      { value: 20, name: '活动景点' }
    ];
  } else if (monthStr === 3 && dateStr === 26) {
    // 3月26日 - 活动景点占比稍高
    occupancyData = [
      { value: 22, name: '茶民宿' },
      { value: 25, name: '茶博物馆' },
      { value: 20, name: '茶馆' },
      { value: 18, name: '文化景点' },
      { value: 35, name: '活动景点' }
    ];
  } else {
    // 其他日期使用动态算法生成，但变化幅度较小
    const baseValue = (dateStr + monthStr) % 10 + 5; // 减小基准数据变化范围
    
    // 每天变化的茶旅管理分布数据，使用较小的变化系数
    occupancyData = [
      { value: 20 + baseValue, name: '茶民宿' },
      { value: 20 + ((baseValue + 2) % 10), name: '茶博物馆' },
      { value: 20 + ((baseValue + 4) % 12), name: '茶馆' },
      { value: 20 + ((baseValue + 1) % 8), name: '文化景点' },
      { value: 20 + ((baseValue + 3) % 10), name: '活动景点' }
    ];
  }
  
  const option = {
    title: {
      text: '',
      left: 'center',
      top: 0,
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}处 ({d}%)'
    },
    legend: {
      show: true,
      orient: 'horizontal',
      bottom: 30,
      left: 'center',
      itemWidth: 20,
      itemHeight: 14,
      itemGap: 20,
      textStyle: {
        fontSize: 14,
        color: '#333'
      },
      data: occupancyData.map(item => item.name)
    },
    series: [
      {
        name: '茶旅管理分布',
        type: 'pie',
        radius: ['25%', '70%'], 
        center: ['50%', '37%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 8
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{d}%',
          fontSize: 12,
          lineHeight: 14,
          color: '#333',
          fontWeight: 'bold',
          backgroundColor: 'rgba(255,255,255,0.7)',
          padding: [4, 6],
          borderRadius: 3
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 10
        },
        emphasis: {
          scale: true,
          scaleSize: 12,
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold',
            formatter: '{d}%',
            color: '#333',
            backgroundColor: 'rgba(255,255,255,0.8)',
            padding: [6, 10],
            borderRadius: 4
          }
        },
        data: occupancyData,
        animationType: 'expansion',
        animationEasing: 'elasticOut',
        animationDuration: 800,
        animationDelay: function(idx) {
          return idx * 100;
        }
      }
    ],
    color: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE']
  };
  
  // 确保图表实例存在
  if (chartInstance.value) {
    // 首次渲染时，使用整个选项
    if (!chartInstance.value.getOption() || Object.keys(chartInstance.value.getOption()).length === 0) {
      chartInstance.value.setOption(option);
    } else {
      // 更新时使用动画效果，减小动画强度
      chartInstance.value.setOption({
        series: [{
          data: occupancyData,
          animation: true,
          animationDuration: 800,
          animationEasing: 'cubicInOut'
        }]
      });
    }
  }
};

// 修改updateWeatherData方法，添加对饼图更新的支持
defineExpose({
  updateWeatherData: (date) => {
    if (date) {
      // 确保date是Date对象
      currentDate.value = date instanceof Date ? date : new Date(date);
    } else {
      currentDate.value = new Date();
    }
    // 在下一个tick更新图表
    setTimeout(() => {
      if (chartInstance.value) {
        if (props.chartType === 'bar') {
          renderBarChart();
        } else if (props.chartType === 'pie') {
          // 更新饼图时启用动画过渡效果
          renderPieChart();
        }
      }
    }, 0);
  }
});
</script>

<style scoped>
.chart-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.chart {
  flex: 1;
  min-height: 270px;
  width: 100%;
  margin-right: -15px;
}
</style> 